<?php
require_once "database/Database.php";


///////////////////////////////////////////////////////////////t
class DatabaseQuery
{
    /*
     * return the instances of class defined by resultClassName
     */
    public static function query ($resultClassName, $queryCondition)
    {
        $field = self::genFieldStringByReflection(new ReflectionClass($resultClassName));     
		$queryCondition->setAction("select " . $field);      
        return Database::execute($queryCondition,$resultClassName);
    }
		
     
	public static function genFieldStringByReflection( $reflectionClass )
	{
	    $props = $reflectionClass->getProperties(ReflectionProperty::IS_PUBLIC);
        $propSize = count($props);
        if ($propSize < 1)
        {
            throw new Exception(
                    "No property is found for " . $reflectionClass->getName() . " . ");
        }
        
        $sql = " ";
        for ($i = 0; $i < $propSize; $i ++)
        {
            if ($i > 0)
            {
                $sql .= ', ';
            }
            $sql .= $props[$i]->getName();
        }
        $sql .= " ";
		
		return $sql;
	}
   
    public static function loadTable($dbTableInstance)
    {
    	if((!is_subclass_of($dbTableInstance,"DbTable")
    			|| $dbTableInstance->getDbName() == NULL
    			|| $dbTableInstance->getDbTableName() == NULL)
    	)
    	{
    		throw new Exception("Invalid parameter for Database::loadTable!");
    	}
    
    	$sqlConditionArray=array();
    	//Assuming that all the attributes in dbTableInstance correspond to the fields in table
    	$reflect=new ReflectionClass($dbTableInstance);
    	$usePriKey=false;	
		$qCondition=new DbBasicSqlStatement();
		
		$field = self::genFieldStringByReflection($reflect); 
		$qCondition->setAction("select " . $field);
		$qCondition->setFrom($dbTableInstance->getDbName() . "." . $dbTableInstance->getDbTableName());
    	if($pk=$dbTableInstance->getDbPrimaryKey()
		   && ($pkValue=$reflect->getProperty($dbTableInstance->getDbPrimaryKey())->getValue($dbTableInstance))
		   )
		{
    		$usePriKey=true;
		}
    
    	if($usePriKey)
    	{
    		$pkInTable=false;
    		$qCondition->addWhere("$pk = ?",array($pkValue));		
    	}
    	else//not use primary key to query
    	{
    		$props   = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
    		foreach($props as $prop)
    		{
    			if($val=$prop->getValue($dbTableInstance))
    			{
					$qCondition->addWhere($prop->getName()."=?",$val);
    			}
    		}
    		
    	}
		$stmt=Database::execute($qCondition);
		if($stmt->rowCount() == 1)
		{
			$ValueArray=$stmt->fetchAll();
			Utility::assignClassProps($dbTableInstance, $ValueArray);
		}
		return $stmt->rowCount();
    }
}

